package study.datastructure.leetcode.javase.primary.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
//单元素枚举类应对反射保证实例唯一性是最有效的安全手段
public class Client {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //Counter counter1 = (Counter) ReflectionUtils.getInstance("Counter");
        Counter counter1 = Counter.INSTANCE;
        Field field = Counter.class.getDeclaredField("INSTANCE");
        field.setAccessible(true);
        Constructor<?> constructor = Counter.class.getDeclaredConstructor(String.class, int.class);
        constructor.setAccessible(true);
        Object instance = constructor.newInstance("", 0);
        field.set(Counter.class, instance);
        if(counter1!=null) {
            System.out.println("counter1: " + counter1);
            int i = 0;
            while (i++ < 10000) {
                Counter counter2 = Counter.INSTANCE;
                if (counter2 != instance) {
                    System.out.println("Got it: " + counter2);
                }
            }
            System.out.println("Done");
        }else{
            System.out.println("Counter1:null");
        }
    }
}